#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'wshu'
__version__ = '1.0'
"""
    ***********************************
    *  @filename : RedisCli.py
    *  @Author : wshu
    *  @CodeDate : 2020/4/15 21:45
    *  @Software : PyCharm
    ***********************************
"""
import redis
import pickle
import threading

class Redis(object):
    """ redis 单例模块 """
    redis = None
    _instance = None
    # 支持多线程，未加锁部分并发执行，加锁部分串行执行
    _instance_lock = threading.Lock()

    @classmethod
    def getInstance(cls, host, port, password, decode_responses):
        with Redis._instance_lock:
            if cls._instance is None:
                cls._instance = cls(host, port, password, decode_responses)
        return cls._instance

    def __init__(self, host, port, password, decode_responses):
        self.pool = redis.ConnectionPool(host=host, port=port, password=password, decode_responses=decode_responses)
        self.redis = redis.StrictRedis(connection_pool=self.pool)

    def setex(self, name, time, value):
        """
        设置值
            time：过期时间(数字秒或timedelta对象)
        """
        return self.redis.setex(name, time, pickle.dumps(value))

    def setnx(self, name, value):
        """
        只有name不存在时，执行设置操作(添加)
        """
        return self.redis.setnx(name, pickle.dumps(value))

    def delete(self, *names):
        return self.redis.delete(*names)

    def get(self, name):
        data = self.redis.get(name)
        try:
            assert data is not None
            return pickle.loads(data)
        except AssertionError as err:
            return None

'''''''''
def test(thread_num):
    print("线程数量:", thread_num)
    host = '10.101.1.246'
    port = 6379
    password = '123'
    redis_instance = Redis(host, port, password, True).getInstance(host, port, password, True)
    print("单例：", redis_instance)

if __name__ == '__main__':
    import time
    host = '10.101.1.246'
    port = 6379
    password = '123'

    for i in range(10):
        t = threading.Thread(target=test, args=[i, ])
        t.start()
    time.sleep(2)
    obj = Redis.getInstance(host, port, password, True)
    print(obj)
'''''''''